import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { showDialog } from 'vant'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: { keepAlive: true },
    },
    {
      path: '/category',
      name: 'category',
      component: () => import('../views/CategoryView.vue'),
    },
    {
      path: '/cart',
      name: 'cart',
      component: () => import('../views/CartView.vue'),
      meta: {
        requireLogin: true,
        title: '购物车',
      },
    },
    {
      path: '/my',
      name: 'my',
      component: () => import('../views/MyView.vue'),
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue'),
    },
    {
      path: '/item',
      name: 'item',
      component: () => import('../views/ItemView.vue'),
    },
    {
      path: '/searchRes',
      name: 'searchRes',
      component: () => import('../views/SearchResultsView.vue'),
    },
    {
      path: '/updateuseravatar',
      name: 'updateuseravatar',
      component: () => import('../views/UpdateUserAvatarView.vue'),
    },
    {
      path: '/updateusername',
      name: 'updateusername',
      component: () => import('../views/UpdateUserNameView.vue'),
    },
    {
      path: '/updatepwd',
      name: 'updatepwd',
      component: () => import('../views/UpdatePasswordView.vue'),
    },
  ],
})

router.beforeEach((to) => {
  let blackList = ['/cart', '/my', '/updatepwd', '/updateuseravatar', '/updateusername']
  if (blackList.includes(to.path)) {
    let token = localStorage.getItem('token')
    if (token == null) {
      showDialog({
        title: '提示',
        message: '请先登录',
      }).then(() => {
        // on close
      })
      return { path: '/login' }
    } else {
      return true
    }
  } else {
    return true
  }
})
export default router
